import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Table, Tag, Alert, Form, Button, Row, Col, Select, Input, Modal, Radio } from 'antd';
import moment from 'moment';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../../utils/common.less';

const DEFAULT_PAGE_SIZE = 20;
const DEFAULT_PAGE_NUM = 1;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Option } = Select;

@connect(({ warehouse, loading }) => ({
  warehouse,
  loading: loading.models.warehouse,
}))
@Form.create()
export default class Warehouse extends PureComponent {
  state = {
    baiJiaPageNum: DEFAULT_PAGE_NUM,
    baiJiaPageSize: DEFAULT_PAGE_SIZE,
    articlePageNum: DEFAULT_PAGE_NUM,
    articlePageSize: DEFAULT_PAGE_SIZE,
    name: '',
    category: '',
    visible: false,
    title: '',
    articleKeywords: '',
    sorted: '',
  };

  componentDidMount() {
    this.initCategory();
    this.fetchTotal();
    this.listBaiJia();
  }

  listBaiJia = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'warehouse/listBaiJia',
      payload: {
        ...this.state,
      },
    });
  };

  listArticle = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'warehouse/listArticle',
      payload: {
        ...this.state,
      },
    });
  };

  fetchTotal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'warehouse/total',
    })
  };

  initCategory= () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'warehouse/listCategory',
    });
  };


  articleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState(
        {
          sorted: fieldsValue.sorted,
          articleKeywords: fieldsValue.keywords,
        },
        () => {
          this.listArticle();
        }
      );
    });
  };

  baiJiaSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState(
        {
          name: fieldsValue.name,
          category: fieldsValue.category,
        },
        () => {
          this.listBaiJia();
        }
      );
    });
  };

  close = () => {
    this.setState({
      visible: false,
    });
  };

  show = record => {
    this.setState(
      {
        title: record.name,
        visible: true,
        baiJiaId: record.id,
      },
      () => {
        this.listArticle(record.id);
      }
    );
  };

  renderBaiJiaForm() {
    const {
      form,
      warehouse: { categoryList },
    } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.baiJiaSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="领域">
              {getFieldDecorator('category')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {categoryList.map(category => (
                    <Option key={category.id} value={category.name}>
                      {category.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <Button type="primary" htmlType="submit" icon="search" style={{ marginLeft: 20 }}>
              查询
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  renderArticleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.articleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="关键字">
              {getFieldDecorator('keywords')(<Input placeholder="请输入希望包含的关键字" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="排序">
              {getFieldDecorator('sorted')(
                <RadioGroup>
                  <Radio value="view">阅读</Radio>
                  <Radio value="comment">评论</Radio>
                </RadioGroup>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <Button type="primary" htmlType="submit" icon="search">
              查询
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      warehouse: { baiJiaList, baiJiaTotal, articleList, articleTotal, total },
      loading,
    } = this.props;
    const {
      baiJiaPageSize,
      baiJiaPageNum,
      articlePageNum,
      articlePageSize,
      visible,
      title,
    } = this.state;

    const that = this;
    const baiJiaPager = {
      total: baiJiaTotal,
      pageSize: baiJiaPageSize,
      current: baiJiaPageNum,
      onChange(current, pageSize) {
        that.setState(
          {
            baiJiaPageNum: current,
            baiJiaPageSize: pageSize,
          },
          () => {
            that.listBaiJia();
          }
        );
      },
    };
    const articlePager = {
      total: articleTotal,
      pageSize: articlePageSize,
      current: articlePageNum,
      onChange(current, pageSize) {
        that.setState(
          {
            articlePageNum: current,
            articlePageSize: pageSize,
          },
          () => {
            that.listArticle();
          }
        );
      },
    };
    const baiJiaColumns = [
      {
        dataIndex: 'name',
        title: '名称',
        width: 200,
      },
      {
        dataIndex: 'follow',
        title: '关注',
        width: 100,
      },
      {
        dataIndex: 'fans',
        title: '粉丝',
        width: 100,
      },
      {
        dataIndex: 'category',
        title: '领域',
        width: 150,
        render: val => (
          <Tag color="blue" key={val}>
            {val}
          </Tag>
        ),
      },
      {
        dataIndex: 'add_time',
        title: '入库时间',
        width: 200,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        dataIndex: 'update_time',
        title: '更新时间',
        width: 200,
        render: val =>
          val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : <span>暂无更新</span>,
      },
      {
        dataIndex: 'description',
        title: '描述',
      },

      {
        dataIndex: 'home_url',
        title: '首页',
        width: 100,
        render: val => (
          <a href={val} target="_bank">
            进入
          </a>
        ),
      },
      {
        title: '操作',
        width: 120,
        render: record => (
          <a
            onClick={() => {
              this.show(record);
            }}
          >
            查看文章
          </a>
        ),
      },
    ];
    const articleColumns = [
      {
        dataIndex: 'title',
        title: '题目',
      },
      {
        dataIndex: 'view',
        title: '阅读',
      },
      {
        dataIndex: 'comment',
        title: '评论',
      },
      {
        dataIndex: 'add_time',
        title: '入库时间',
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        dataIndex: 'publish_time',
        title: '发布时间',
      },
      {
        dataIndex: 'update_time',
        title: '更新时间',
        render: val =>
          val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : <span>暂无更新</span>,
      },
      {
        title: '操作',
        render: val => (
          <a href={val.src} target="_bank">
            查看
          </a>
        ),
      },
    ];
    const message = (
      <div>
        <span>每天早6点开始追加百家号,同时更新粉丝数、关注数.</span>
      </div>
    );
    const content = (
      <div>
        当前已抓取百家号 <span style={{ color:'red', fontSize: 20}}>{ total }</span> 个, 爬虫状态: <span style={{ color: 'green', fontSize: 18}}> 运行中...</span>
      </div>
    );
    return (
      <PageHeaderLayout
        title="百家号列表"
        content={content}
      >
        <Card bordered={false}>
          <Alert message={message} type="info" showIcon style={{ marginBottom: '20px' }} closable />
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderBaiJiaForm()}</div>
            <Table
              bordered={false}
              dataSource={baiJiaList}
              columns={baiJiaColumns}
              loading={loading}
              rowkey={record => record.id}
              pagination={baiJiaPager}
            />
          </div>
        </Card>
        <Modal
          visible={visible}
          title={`${title} - 的文章`}
          onOk={this.close}
          onCancel={this.close}
          width="80%"
        >
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderArticleForm()}</div>
            <Table
              bordered={false}
              dataSource={articleList}
              columns={articleColumns}
              loading={loading}
              rowkey={record => record.id}
              pagination={articlePager}
            />
          </div>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
